
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;


public class StorageServerQ implements Runnable {

    private ConcurrentLinkedQueue<ReplyTo> orders;
    private final int time = 600;
    ObjectOutputStream outToClient;
    Connection conn;
    DB db;


    public StorageServerQ(ConcurrentLinkedQueue<ReplyTo> orders) throws Exception {
        this.orders = orders;
        this.conn = db.getConnection();
    }


    public void run() {

        while (true) {
            for (ReplyTo r : orders) {
                //System.out.println(r.getData().values().toString());

                if (r.getRequest().getOp().equals("put")) {
                    for (Integer i : r.getRequest().getData().keySet()) {
                        try {

                            db.writeJavaObject(conn, i.intValue(), r.getRequest().getData().get(i));
                            
                        } catch (Exception ex) {
                            Logger.getLogger(StorageServerQ.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    orders.remove();


                } else if (r.getRequest().getOp().equals("get")) {
                    Request answer = new Request();
                    for (Integer i : r.getRequest().getData().keySet()) {

                        try {

                            byte[] obj;
                            obj = (byte[]) db.readJavaObject(conn,i.intValue());
                            answer.getData().put(i, obj);
                            
                        } catch (Exception ex) {
                            Logger.getLogger(StorageServerQ.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    try {
                        //Envia resposta para o Cliente
                        outToClient = new ObjectOutputStream(r.getSocket().getOutputStream());
                        outToClient.writeObject(answer);
                        outToClient.close();
                    } catch (IOException ex) {
                        Logger.getLogger(StorageServerQ.class.getName()).log(Level.SEVERE, null, ex);
                    }


                    orders.remove();
                } else {
                    System.out.println("Error in requested operation!");
                    orders.remove();
                }


            }
            try {
                Thread.sleep(time);
            } catch (InterruptedException ex) {
                Logger.getLogger(StorageServerQ.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}
